<template>
  <el-dialog 
    title="配置条件显示规则" 
    :visible.sync="dialogVisible"
    width="500px"
    append-to-body
    @closed="handleDialogClosed"
  >
    <el-form :model="localRule" label-width="120px" class="condition-form" ref="conditionForm">
      <el-form-item label="触发参数" prop="triggerParam">
        <el-select 
          v-model="localRule.triggerParam" 
          size="mini"
          placeholder="选择触发显示的参数"
          style="width: 100%;"
        >
          <el-option 
            v-for="param in allBaseParams"
            :key="param.paramCode"
            :label="`${param.paramName}（${param.paramCode}）`"
            :value="param.paramCode"
          ></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="匹配逻辑" prop="matchType">
        <el-select v-model="localRule.matchType" size="mini" style="width: 100%;">
          <el-option label="等于" value="eq"></el-option>
          <el-option label="不等于" value="ne"></el-option>
          <el-option label="包含" value="contain"></el-option>
          <el-option label="不包含" value="notContain"></el-option>
          <el-option label="大于" value="gt"></el-option>
          <el-option label="大于等于" value="ge"></el-option>
          <el-option label="小于" value="lt"></el-option>
          <el-option label="小于等于" value="le"></el-option>
          <el-option label="为空" value="empty"></el-option>
          <el-option label="不为空" value="notEmpty"></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item 
        label="触发值" 
        prop="triggerValue"
        v-if="!['empty', 'notEmpty'].includes(localRule.matchType)"
      >
        <el-input 
          v-model="localRule.triggerValue" 
          size="mini" 
          placeholder="输入触发显示的值"
          style="width: 100%;"
        ></el-input>
      </el-form-item>
      
      <el-form-item label="默认状态" prop="defaultShow">
        <el-select v-model="localRule.defaultShow" size="mini" style="width: 100%;">
          <el-option label="默认隐藏（满足条件显示）" value="hide"></el-option>
          <el-option label="默认显示（不满足条件隐藏）" value="show"></el-option>
        </el-select>
      </el-form-item>

      <!-- 规则预览 -->
      <el-form-item label="规则预览">
        <div class="rule-preview">
          <p>{{ ruleDescription }}</p>
        </div>
      </el-form-item>
    </el-form>
    
    <div slot="footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSave" :loading="saving">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { cloneDeep } from 'lodash';

export default {
  name: 'ConditionRuleDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    rule: {
      type: Object,
      required: true,
      default: () => ({
        triggerParam: '',
        matchType: 'eq',
        triggerValue: '',
        defaultShow: 'hide'
      })
    },
    allBaseParams: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      localRule: this.getDefaultRule(),
      saving: false
    };
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible;
      },
      set(value) {
        this.$emit('update:visible', value);
      }
    },
    
    // 规则描述预览
    ruleDescription() {
      if (!this.localRule.triggerParam || !this.localRule.matchType) {
        return '请完善规则配置';
      }
      
      const triggerParam = this.allBaseParams.find(
        param => param.paramCode === this.localRule.triggerParam
      );
      const paramName = triggerParam ? triggerParam.paramName : this.localRule.triggerParam;
      
      const matchTextMap = {
        'eq': '等于',
        'ne': '不等于',
        'contain': '包含',
        'notContain': '不包含',
        'gt': '大于',
        'ge': '大于等于',
        'lt': '小于',
        'le': '小于等于',
        'empty': '为空',
        'notEmpty': '不为空'
      };
      
      const matchText = matchTextMap[this.localRule.matchType] || this.localRule.matchType;
      
      let conditionText = '';
      if (['empty', 'notEmpty'].includes(this.localRule.matchType)) {
        conditionText = `当参数"${paramName}" ${matchText}时`;
      } else {
        conditionText = `当参数"${paramName}" ${matchText} "${this.localRule.triggerValue}"时`;
      }
      
      const actionText = this.localRule.defaultShow === 'hide' 
        ? '显示此字段' 
        : '隐藏此字段';
      
      return `${conditionText}，${actionText}`;
    },
    
    // 表单验证
    isFormValid() {
      if (!this.localRule.triggerParam) return false;
      if (!this.localRule.matchType) return false;
      if (!['empty', 'notEmpty'].includes(this.localRule.matchType) && !this.localRule.triggerValue) {
        return false;
      }
      if (!this.localRule.defaultShow) return false;
      return true;
    }
  },
  watch: {
    visible: {
      handler(newVal) {
        if (newVal) {
          this.initLocalRule();
        }
      },
      immediate: true
    },
    rule: {
      handler() {
        if (this.visible) {
          this.initLocalRule();
        }
      },
      deep: true
    }
  },
  methods: {
    // 获取默认规则
    getDefaultRule() {
      return {
        triggerParam: '',
        matchType: 'eq',
        triggerValue: '',
        defaultShow: 'hide'
      };
    },

    // 初始化本地规则
    initLocalRule() {
      this.localRule = cloneDeep(this.rule) || this.getDefaultRule();
    },

    // 处理保存
    handleSave() {
      if (!this.isFormValid) {
        this.$message.warning('请完善条件显示规则配置');
        return;
      }

      this.saving = true;
      
      // 发出保存事件，传递本地规则
      this.$emit('save', cloneDeep(this.localRule));
      
      // 延迟关闭对话框，确保父组件有足够时间处理
      setTimeout(() => {
        this.dialogVisible = false;
        this.saving = false;
      }, 100);
    },

    // 处理取消
    handleCancel() {
      this.dialogVisible = false;
    },

    // 处理对话框关闭
    handleDialogClosed() {
      // 重置本地规则
      this.localRule = this.getDefaultRule();
      // 重置表单验证
      if (this.$refs.conditionForm) {
        this.$refs.conditionForm.clearValidate();
      }
    }
  }
};
</script>

<style scoped>
.condition-form {
  margin-top: 10px;
}

.condition-form .el-form-item {
  margin-bottom: 18px;
}

.rule-preview {
  background: #f0f9ff;
  border: 1px solid #91d5ff;
  border-radius: 4px;
  padding: 12px;
  font-size: 13px;
  line-height: 1.5;
  color: #1890ff;
}

.rule-preview p {
  margin: 0;
}
</style>